import Vue from 'vue';
import Router from 'vue-router';
import front from './front.js';
import {
	refreshToken, authLogin
} from '../api/index.js';
import Cookies from 'js-cookie'; //Cookies缓存

Vue.use(Router);

//跳转同路由不报错处理
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
	if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
	return originalPush.call(this, location).catch(err => err)
}


let routes = [{
	path: '/',
	redirect: '/index'
},
{
	path: '/',
	component: () => import( /* webpackChunkName: "home" */ '../components/common/Home.vue'),
	meta: {
		title: '自述文件'
	},
	children: [
		// 概况
		{
			path: '/index',
			name: 'index',
			component: () => import('@/view/index/index.vue'),
			meta: {
				title: '概况'
			}
		},
		//店铺装修
		{
			path: '/wapShop',
			component: () => import('@/view/shop/wapShop.vue'),
			meta: {
				title: '移动端店铺'
			}
		},
		// {
		//     path: '/pcShop',
		//     component: () => import('@/view/shop/pcShop.vue'),
		//     meta: { title: '电脑端店铺' }
		// },
		{
			path: '/custom',
			component: () => import('@/view/shop/custom.vue'),
			meta: {
				title: '自定义页面'
			}
		},
		{
			path: '/h5_iframe',
			component: () => import('@/view/shop/h5_iframe.vue'),
			meta: {
				title: '查看页面'
			}
		},
		{
			path: '/new_user_list',
			component: () => import('@/view/index/new_user_list.vue'),
			meta: {
				title: '付费用户列表'
			}
		},
		{
			path: '/custom/customphone',
			component: () => import('@/view/shop/customphone.vue'),
			meta: {
				title: '用户自定义手机页面'
			}
		},
		{
			path: '/nav',
			component: () => import('@/view/shop/nav.vue'),
			meta: {
				title: '底部导航'
			}
		},
		//内容类型
		{
			path: '/classification',
			component: () => import('@/view/courseList/classification.vue'),
			meta: {
				title: '分类'
			}
		},
		{
			path: '/fenzu',
			component: () => import('@/view/courseList/fenzu.vue'),
			meta: {
				title: '分组'
			}
		},
		{
			path: '/article',
			component: () => import('@/view/courseList/article.vue'),
			meta: {
				title: '图文'
			}
		},
		{
			path: '/audio',
			component: () => import('@/view/courseList/audio.vue'),
			meta: {
				title: '音频'
			}
		},
		{
			path: '/video',
			component: () => import('@/view/courseList/video.vue'),
			meta: {
				title: '视频'
			}
		},
		{
			path: '/package',
			component: () => import('@/view/courseList/package.vue'),
			meta: {
				title: '专栏'
			}
		},
		{
			path: '/package/columnManage',
			component: () => import('@/view/courseList/columnManage.vue'),
			name: 'columnManage',
			meta: {
				title: '专栏内容管理',
				//keepAlive:false
			}
		},
		//直播
		{
			path: '/small_class',
			component: () => import('@/view/live/small_class.vue'),
			meta: {
				title: '公开课'
			}
		},
		{
			path: '/live_pushFlow',
			component: () => import('@/view/live/live_pushFlow.vue'),
			meta: {
				title: '第三方推流'
			}
		},
		//助学工具
		{
			path: '/examination',
			component: () => import('@/view/aidTool/examination.vue'),
			meta: {
				title: '试卷'
			}
		},
		{
			path: '/examManage',
			component: () => import('@/view/aidTool/examManage.vue'),
			meta: {
				title: '试题管理'
			}
		},
		{
			path: '/exercise',
			component: () => import('@/view/aidTool/exercise.vue'),
			meta: {
				title: '作业本'
			}
		},
		{
			path: '/questionbank',
			component: () => import('@/view/aidTool/questionbank.vue'),
			meta: {
				title: '题库'
			}
		},
		{
			path: '/questionbank_detail',
			component: () => import('@/view/aidTool/questionbank_detail.vue'),
			meta: {
				title: '试题列表'
			}
		},
		{
			path: '/certificate',
			component: () => import('@/view/aidTool/certificate.vue'),
			meta: {
				title: '证书'
			}
		},
		{
			path: '/exam',
			component: () => import('@/view/aidTool/exam.vue'),
			meta: {
				title: '考试'
			}
		},
		{
			path: '/answerDetail',
			component: () => import('@/view/aidTool/answerDetail.vue'),
			meta: {
				title: '答题详情'
			}
		},
		{
			path: '/answer_record',
			component: () => import('@/view/aidTool/answer_record.vue'),
			meta: {
				title: '答题记录'
			}
		},
		//讲师管理
		{
			path: '/lecturer_login',
			component: () => import('@/view/lecturerManage/lecturer_login.vue'),
			meta: {
				title: '讲师登录'
			}
		},
		{
			path: '/lecturer_list',
			component: () => import('@/view/lecturerManage/lecturer_list.vue'),
			meta: {
				title: '讲师列表'
			}
		},
		{
			path: '/lecturer_commission',
			component: () => import('@/view/lecturerManage/lecturer_commission.vue'),
			meta: {
				title: '讲师佣金'
			}
		},
		{
			path: '/lecturer_withdraw',
			component: () => import('@/view/lecturerManage/lecturer_withdraw.vue'),
			meta: {
				title: '讲师提现'
			}
		},
		{
			path: '/lecturer_set',
			component: () => import('@/view/lecturerManage/lecturer_set.vue'),
			meta: {
				title: '讲师配置'
			}
		},
		//用户管理
		{
			path: '/user_list',
			component: () => import('@/view/userManage/user_list.vue'),
			meta: {
				title: '用户列表'
			}
		},
		{
			path: '/member_settings',
			component: () => import('@/view/userManage/member_settings.vue'),
			meta: {
				title: '会员设置'
			}
		},
		{
			path: '/member_list',
			component: () => import('@/view/userManage/member_list.vue'),
			meta: {
				title: '会员列表'
			}
		},
		//交易
		{
			path: '/order_list',
			component: () => import('@/view/orderManage/order_list.vue'),
			meta: {
				title: '订单管理'
			}
		},
		{
			path: '/order_list/order_detail',
			component: () => import('@/view/orderManage/order_detail.vue'),
			meta: {
				title: '订单详情'
			}
		},
		//营销中心
		{
			path: '/marketingPlay',
			component: () => import('@/view/market/marketingPlay.vue'),
			meta: {
				title: '营销玩法'
			}
		},
		{
			path: '/promoter',
			component: () => import('@/view/market/promoter.vue'),
			meta: {
				title: '推广员'
			}
		},
		{
			path: '/inviteCode',
			component: () => import('@/view/market/inviteCode.vue'),
			meta: {
				title: '邀请码',
			}
		},
		{
			path: '/activation_code',
			component: () => import('@/view/market/activation_code.vue'),
			meta: {
				title: '激活码'
			}
		},
		{
			path: '/inviteFriendSee',
			component: () => import('@/view/market/inviteFriendSee.vue'),
			meta: {
				title: '请好友看'
			}
		},
		{
			path: '/coupon',
			component: () => import('@/view/market/coupon.vue'),
			meta: {
				title: '优惠劵'
			}
		},
		{
			path: '/couponNew',
			component: () => import('@/view/market/couponNew.vue'),
			meta: {
				title: '优惠劵(新)'
			}
		},
		{
			path: '/collage',
			component: () => import('@/view/market/collage.vue'),
			meta: {
				title: '拼团'
			}
		},
		{
			path: '/increaseFans',
			component: () => import('@/view/market/increaseFans.vue'),
			meta: {
				title: '涨粉神器'
			}
		},
		{
			path: '/seckill',
			component: () => import('@/view/market/seckill.vue'),
			meta: {
				title: '秒杀'
			}
		},
		{
			path: '/limitDiscount',
			component: () => import('@/view/market/limitDiscount.vue'),
			meta: {
				title: '限时折扣'
			}
		},
		{
			path: '/goodsRecommend',
			component: () => import('@/view/market/goodsRecommend.vue'),
			meta: {
				title: '商品推荐'
			}
		},
		{
			path: '/advertisePop',
			component: () => import('@/view/market/advertisePop.vue'),
			meta: {
				title: '弹窗广告'
			}
		},
		{
			path: '/payPolitely',
			component: () => import('@/view/market/payPolitely.vue'),
			meta: {
				title: '支付有礼'
			}
		},
		{
			path: '/exchangeCode',
			component: () => import('@/view/market/exchangeCode.vue'),
			meta: {
				title: '兑换码'
			}
		},
		{
			path: '/exchangeCodeList',
			component: () => import('@/view/market/exchangeCodeList.vue'),
			meta: {
				title: '兑换码列表'
			}
		},
		//设置
		{
			path: '/setshop',
			component: () => import('@/view/setting/setshop.vue'),
			meta: {
				title: '店铺设置'
			}
		},
		{
			path: '/announce_manage',
			component: () => import('@/view/setting/announce_manage.vue'),
			meta: {
				title: '公告管理'
			}
		},
		{
			path: '/suggest',
			component: () => import('@/view/setting/suggest.vue'),
			meta: {
				title: '建议/意见'
			}
		},
		{
			path: '/staff',
			component: () => import('@/view/setting/staff.vue'),
			meta: {
				title: '员工管理'
			}
		},
		{
			path: '/staffauth',
			component: () => import('@/view/setting/staffauth.vue'),
			meta: {
				title: '员工权限'
			}
		},
		{
			path: '/opLog',
			component: () => import('@/view/setting/opLog.vue'),
			meta: {
				title: '操作日志'
			}
		},
		{
			path: '/menuSort',
			component: () => import('@/view/setting/menuSort.vue'),
			meta: {
				title: '拖拽菜单'
			}
		},
		//服务
		{
			path: '/service_buy',
			component: () => import('@/view/service/service_buy.vue'),
			meta: {
				title: '服务订购'
			}
		},
		//权限管理
		{
			path: '/accountManage',
			component: () => import('@/view/limitsManage/accountManage.vue'),
			meta: {
				title: '账号管理'
			}
		},
		{
			path: '/accountLimits',
			component: () => import('@/view/limitsManage/accountLimits.vue'),
			meta: {
				title: '账号权限'
			}
		},
		
		{
			path: '/set_kefu',
			component: () => import('@/view/message/set_kefu.vue'),
			meta: {
				title: "设置客服"
			}
		},
		{
			path: '/reply_msg',
			component: () => import('@/view/message/reply_msg.vue'),
			meta: {
				title: "回复信息"
			}
		}, {
			path: '/refund_list',
			component: () => import('@/view/orderManage/refund_list.vue'),
			meta: {
				title: "退款订单"
			}
		}, {
			path: '/refund_list/refund_detail',
			component: () => import('@/view/orderManage/refund_detail.vue'),
			meta: {
				title: '退款详情'
			}
		}, {
			path: '/schoolpay_list',
			component: () => import('@/view/orderManage/schoolpay_list.vue'),
			meta: {
				title: "网校提现订单"
			}
		},
		{
			path: '/teamwork',
			component: () => import('@/view/market/teamwork.vue'),
			meta: {
				title: '拼团'
			},
			children: [
				{
					path: '/',
					component: () => import('@/view/market/teamwork_index.vue'),
					meta: {
						title: '拼团'
					},
				},
				{
					path: 'create_team',
					component: () => import('@/view/market/createTeam.vue'),
					meta: {
						title: '拼团'
					},
				},
				{
					path: 'view_team',
					component: () => import('@/view/market/viewTeam.vue'),
					meta: {
						title: '拼团'
					},
				}
			]
		},
		{
			path: '/payGifts',
			component: () => import('@/view/market/payGifts.vue'),
			meta: {
				title: '支付有礼'
			},
			children: [
				{
					path: '/',
					component: () => import('@/view/market/payGifts_index.vue'),
					meta: {
						title: '支付有礼'
					}
				},
				{
					path: 'freeTrial',
					component: () => import('@/view/market/payGiftsFreeTrial.vue'),
					meta: {
						title: '支付有礼'
					}
				},
				{
					path: 'create_payGifts',
					component: () => import('@/view/market/createFreeTrial.vue'),
					meta: {
						title: '支付有礼'
					}
				}
			]
		}
	]
},
{
	path: '/login',
	component: () => import( /* webpackChunkName: "login" */ '../components/page/Login.vue'),
	meta: {
		title: '登录',
		permission: true //直接通过
	}
},
{
	path: '/myShop',
	component: () => import('@/view/shop/myShop.vue'),
	meta: {
		title: '我的店铺'
	}
},
{
	path: '*',
	redirect: '/404'
},
{
	path: '/refresh',
	component: resolve => require(['@/view/refresh/refresh.vue'], resolve),
	meta: {
		title: '用于同路由刷新'
	}
},
{
	path: '/tmpshop',
	component: () => import('@/view/shop/tmpshop.vue'),
	meta: {
		title: '店铺预览'
	}
},
{
	path: '/test',
	component: () => import('@/view/shop/test.vue'),
	meta: {
		title: '用户自定义页面'
	}
},
{
	path: '/test7/kefuchat',
	component: () => import('../view/shop/kefuchat.vue'),
	name: "test7kefuchat",
	meta: {
		title: '客服聊天框'
	}
}
];

// front.forEach((item) => {
// 	routes.push(item);
// })

routes.push(...front);

let router = new Router({ mode: 'history', routes });

// router.selfaddRoutes = function (params){
// 	router.matcher = new Router().matcher;
// 	router.addRoutes(params)
//   }

//使用钩子函数对路由进行权限跳转
var islogin = false;//判断需要是否重新登录
router.beforeEach((to, from, next) => {
	document.title = `知了 | ${to.meta.title}`;
	var that = router.app;
	//--------前端验证开始
	if (isWeixin()) {//如果没有登录又是需要登录的页面就跳转到登录页
		if(to.path.search('exampreview') != -1){
			next();
			return;
		}

		
		if(to.path.search('downfiles') != -1){
			next();
			return;
		}

		var logintag = sessionStorage.getItem('logintag') ? sessionStorage.getItem('logintag') : 0;
		if (to.meta.verify && logintag == 0) {
			that.$router.push({ name: 'my' });
			return;
		}
	} else {
		// var logintag = sessionStorage.getItem('htmllogintag') ? sessionStorage.getItem('htmllogintag') : 0;
		// if (to.meta.verify && logintag == 0 ) {
		// 	that.$router.push({ name: 'my', query: { islogin: 1 } });
		// 	return;
		// }
	}
	if (to.meta.verify ) {//访问需要验证的页面都要判断一下token是否过期，需要是否重新发token，在登录状态则通过
		
		// const frontrefreshtoken = Cookies.get('frontrefreshtoken') ? Cookies.get('frontrefreshtoken') || localStorage.getItem('frontrefreshtoken') : "";
		// that.$frontaxios.post(that.$front.frontRefreshToken, { frontrefreshtoken, phone: localStorage.getItem('phone') }).then((res) => {
		// 	console.log(res);
		// 	if (res.code == 1) {//重新颁发前台token
		// 		let fronttoken = res.data.fronttoken;
		// 		Cookies.set('fronttoken', fronttoken);
		// 		localStorage.setItem('fronttoken', res.data.token);
		// 		next();
		// 	} else if (res.code == 2) {//token没过期,在登录状态就跳转到路由
		// 		next();
		// 	} else if (res.code == -10 && !com) {
		// 		that.$dialog.alert({ title: "温馨提示", message: "店铺使用期限已到，请购买后再来查看" }); return;
		// 	}
		// 	else {//刷新token和token都过期跳转到登录页面
		// 		islogin = true; //跳转到指定的店铺登录页，设为true判断是否要重新登录
		// 		next();
		// 	}
		// })
		// return;
	}
	if (to.path.search('/shop') != -1 || to.path.search('/xuejing') != -1) { //如果前端不需要验证，到这里就直接通过
		next(); return;
	}
	//----前端验证结束
	//----后台登录验证开始
	if(to.path.search('exampreview') != -1){
		next();
		return;
	}
	
	const role = Cookies.get('token');
	if (!role && to.path !== '/login') {
		next('/login');
	} else if (!to.meta.permission) {//除了login页面都要经过这个页面进行判断token是否过期，如果过期就重新给他一个新token,如果刷新token过期就重新登录
		const refreshtoken = Cookies.get('refreshtoken') ? Cookies.get('refreshtoken') : "";
		refreshToken({ refreshtoken, username: localStorage.getItem('ms_username'), shopuuid: localStorage.getItem('shopuuid') }).then((res) => {
			// console.log(res);
			if (res.code == 1) {
				let token = res.data.token;
				Cookies.set('token', token);
				next();
			} else if (res.code == 2) {
				next();
			}
			else {
				next('/login');
				// next();
			}
		})
		//role === 'admin' ? next() : next('/403');
	} else {
		// 简单的判断IE10及以下不进入富文本编辑器，该组件不兼容
		if (navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor') {
			that.$confirm('vue-quill-editor组件不兼容IE10及以下浏览器，请使用更高版本的浏览器查看', '浏览器不兼容通知', {
				confirmButtonText: '确定'
			});
		} else {
			next();
		}
	}
	//-----后台验证结束
});

//进了页面以后验证
router.afterEach((to, from) => {
	//---前端验证开始
	if (to.path.search('/shop') != -1 || to.path.search('/xuejing') != -1) { //如果前端不需要验证，到这里就直接通过
		var that = router.app;
		if (that.$route.params.domainname) {
			Cookies.set('frontdomainname', that.$route.params.domainname);
			localStorage.setItem('domainname', that.$route.params.domainname);
		}
		that.$frontaxios.post(that.$front.getShopName).then((res) => {
			if (res.code == 1) {
				localStorage.setItem('shopname', res.data.shopname)
			} else {
				console.log('获取店铺名失败');
			}
		});
		if (islogin) { //需要重新登录
			Cookies.remove("fronttoken");
			Cookies.remove("frontrefreshtoken");
			localStorage.clear();
			sessionStorage.clear();
			islogin = false; //设置为false防止下次进来还跳转
			router.push({ name: 'my', query: { islogin: 1 } });
			//router.push({path:'/xuejing/my/'+that.$route.params.domainname,query:{islogin:1}});
			return;
		}
	}//---前端验证结束
	//---后台验证开始
	else if (to.path.search('/myShop') == -1 && to.path.search('/login') == -1 && to.path.search('/index') == -1) {
		var that = router.app;
		authLogin({ path: to.path }).then((res) => {
			if (res.code == -1) {//不允许进入该页面
				//否则就是没有权限进入该页面
				that.$alert('非法操作,你没有权限', '消息提示', {
					confirmButtonText: '确定',
					callback: action => {
						that.$router.back();
					}
				});
			}
		})
	}
	//---后台验证结束
})

export default router;
